package work.soho.proxy.aliyun.parts;

import com.aliyuncs.ecs.model.v20140526.CreateVpcRequest;
import com.aliyuncs.ecs.model.v20140526.CreateVpcResponse;
import com.aliyuncs.ecs.model.v20140526.DescribeVpcsRequest;
import com.aliyuncs.ecs.model.v20140526.DescribeVpcsResponse;

/**
 * 虚拟网络管理
 */
public class VpcPart extends BasePart implements IPart{
    private String vpcName = "proxySocket5vpc";

    @Override
    public boolean isExist() {
        return getId() != null;
    }

    /**
     * 获取专有网络ID
     *
     * @return
     */
    public String getId() {
        DescribeVpcsRequest describeVpcsRequest = new DescribeVpcsRequest();
        describeVpcsRequest.setRegionId(regionId);

        DescribeVpcsResponse describeVpcsResponse = (DescribeVpcsResponse) callOpenApi(describeVpcsRequest);
        for (DescribeVpcsResponse.Vpc vpc: describeVpcsResponse.getVpcs()) {
            if(vpc.getVpcName().equals(vpcName)) {
                return vpc.getVpcId();
            }
        }
        return null;
    }

    @Override
    public void drop() {
        //nothing todo
    }

    @Override
    public void create() throws AliyunPartsException {
        try {
            CreateVpcRequest createVpcRequest = new CreateVpcRequest();
            createVpcRequest.setRegionId(regionId);
            createVpcRequest.setVpcName(vpcName);
            CreateVpcResponse createVpcResponse =  callOpenApi(createVpcRequest);
            configure.setVpcId(createVpcResponse.getVpcId());
        } catch (Exception e) {
            throw new AliyunPartsException("创建虚拟网络失败， 请检查相关配置信息是否正确。");
        }

    }

    @Override
    public void start() {
        //nothing todo
    }

    @Override
    public void configure() {
        configure.setVpcId(getId());
    }
}
